/**
 * 
 */
package com.jeesuite.bestpl.service;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import com.jeesuite.bestpl.api.IUserService;
import com.jeesuite.bestpl.dao.entity.UserEntity;
import com.jeesuite.bestpl.dao.mapper.UserEntityMapper;
import com.jeesuite.bestpl.dto.User;
import com.jeesuite.bestpl.dto.request.OpenIdBindRequest;
import com.jeesuite.bestpl.dto.request.RegisterRequest;
import com.jeesuite.bestpl.dto.request.UpdatePasswordRequest;
import com.jeesuite.bestpl.dto.request.UpdateUserRequest;
import com.jeesuite.bestpl.exception.DemoBaseException;
import com.jeesuite.bestpl.exception.UserNoExistException;
import com.jeesuite.common.util.BeanCopyUtils;
import com.jeesuite.common.util.DigestUtils;

/**
 * @description <br>
 * @author <a href="mailto:vakinge@gmail.com">vakin</a>
 * @date 2016年10月25日
 */
@Service("userService")
public class UserServiceImpl implements IUserService {

	/**
	 * 密码加密盐
	 */
	private static final String PASSWORD_SALT = "~w56!@#$%vg";

	@Autowired
	private UserEntityMapper userMapper;
	
	@Autowired
	private TransactionTemplate transactionTemplate;

	@Override
	public User getUser(Integer userId) throws UserNoExistException {
		UserEntity entity = userMapper.selectByPrimaryKey(userId);
		if(entity == null)throw new UserNoExistException();
		return BeanCopyUtils.copy(entity, User.class);
	}

	@Override
	@Transactional
	public User register(RegisterRequest request) {
		
		UserEntity entity = new UserEntity();
		entity.setName(request.getName());
		entity.setMobile(request.getMobile());
		entity.setPassword(DigestUtils.md5WithSalt(request.getPassword(), PASSWORD_SALT));
		entity.setRegisterAt(new Date());
		
		userMapper.insertSelective(entity);
		
		return BeanCopyUtils.copy(entity, User.class);
	}

	@Override
	public User registerByOpenId(OpenIdBindRequest request) {
        		
		return null;
	}

	@Override
	public User login(String loginName, String password) {
		//TODO BY NAME,EMAIL
		UserEntity entity = userMapper.findByMobile(loginName);
		if(entity == null)throw new UserNoExistException();
		if(!StringUtils.equals(DigestUtils.md5WithSalt(password, PASSWORD_SALT), entity.getPassword())){
			throw new DemoBaseException(1002, "密码错误");
		}
		return BeanCopyUtils.copy(entity, User.class);
	}

	@Override
	public void updateUserInfo(UpdateUserRequest request) {}

	@Override
	public void removeUser(Integer userId) throws UserNoExistException {}

	@Override
	public void updatePassword(UpdatePasswordRequest request) {}

	@Override
	public void bindOpenId(OpenIdBindRequest request) {}


	@Override
	public void unbindOpenId(int userId, int openId) {}

	

}
